<!--renshuai-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="tagName">
        <el-input
            v-model="queryParams.tagName"
            placeholder="名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option  v-for="(item,index) in statusList" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['cms:doctag:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tagList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="50px" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="tagName" :show-overflow-tooltip="true"/>
      <el-table-column label="ICON" align="center" prop="tagName" >
        <template slot-scope="scope">
          <el-image
              style="width: 30px; height: 30px; margin-bottom:-4px"
              :src="scope.row.iconUrl"
              :preview-src-list="[scope.row.iconUrl]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <dict-tag :options="statusList" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['cms:doctag:edit']">修改</el-button>
          <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['cms:doctag:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body center :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-input type="hidden" v-model="form.pkId"></el-input>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="tagName">
              <el-input v-model="form.tagName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ICON">
              <el-upload
                  class="thmb-uploader"
                  :action="uploadAction"
                  accept="image/jpg,image/png,image/jpeg"
                  :on-exceed="handleExceed"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :headers="headers"
                  :auto-upload="true" :file-list="fileList"
                  :on-success="handleSuccessImg" :on-remove="handleRemove"
              >
                <img v-if="form.iconUrl" :src="form.iconUrl" class="thmb-img">
                <i v-else class="el-icon-plus thmb-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="状态" prop="status">
              <el-switch
                  v-model="form.status"
                  active-value="1"
                  inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="绑定内容" prop="docId">
              <el-select v-model="form.docList[0].pkId" filterable placeholder="请选择" clearable >
                <el-option
                    v-for="(item,index) in dictDocList"
                    :key="index"
                    :label="item.title"
                    :value="item.pkId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitForm">保 存</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {delTag, getDocTagDetails, getTagById, listDoc, listTag, updateTag} from "@/api/cms/doc";
import {uploadFile} from "@/api/upload";
import {getSystem, getToken} from "@/utils/auth";

export default {
  name: "TagList",
  data() {
    return {
      uploadAction:uploadFile,
      headers: {
        // Authorization: "Bearer " + getToken()
        'access-token': getToken(), // 让每个请求携带自定义token 请根据实际情况自行修改
        'system-key': getSystem()
      },
      fileList:[],
      statusList:[
        {
          raw:{
            listClass:"default",
            cssClass:""
          },
          value:"",
          label:"全部"
        },
        {
          raw:{
            listClass:"primary",
            cssClass:""
          },
          value:"1",
          label:"正常"
        },
        {
          raw:{
            listClass:"info",
            cssClass:""
          },
          value:"0",
          label:"关闭"
        }
      ],
      dictDocList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tagList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        tagName: undefined,
      },
      // 表单参数
      form: {
        docList:[
          {
            pkId:undefined
          }
        ],
      },
      // 表单校验
      rules: {
        tagName:  [
          {
            validator:(rule, value, callback)=>{
              if(value ===""){
                callback(new Error("标题不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '标题不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getListDoc();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listTag(this.queryParams).then(response => {
        this.tagList = response.data;
        this.total = response.total != NaN ?Number(response.total):undefined
        this.loading = false;
      });
    },
    getListDoc(){
      let query={
        pageNum: 1,
        pageSize: 100,
      }
      listDoc(query).then(response => {
        this.dictDocList = response.data;
      });
    },

    /**
     * 详情按钮
     * @param row
     */
    handleUpdate(row){
      let pkId=row.pkId;
      getTagById(pkId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "详细信息";

        getDocTagDetails({tagId:this.form.pkId}).then(response =>{
          if(response.data){
            this.$set(this.form,"docList", [{pkId:response.data.pkId}])
          }else{
            this.$set(this.form,"docList", [{pkId:undefined}])
          }

        })

      });
    },

    handleAdd(){
      this.reset();
      this.open = true;
      this.title = "新增";
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.tagName + '"的数据项？').then(function() {
        return delTag(row.pkId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },


    onSubmitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateTag(this.form).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    // 取消按钮
    handleClose() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pkId:undefined,
        status:"1",
        tagName:undefined,
        iconUrl:undefined,
        docList:[
          {
            pkId:undefined
          }
        ],
        // noticeId: undefined,
        // noticeTitle: undefined,
        // noticeType: undefined,
        // noticeContent: undefined,
        // status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },


    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多上传一张图片`)
    },
    beforeAvatarUpload(file) {
      let isJPG = false
      let isLt10M = file.size / 1024 / 1024 < 10
      if (
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/jpg'
      ) {
        isJPG = true
      } else {
        isJPG = false
      }
      if (!isJPG) {
        this.$message.error('上传图片只能是 jpg/jpeg/png 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10M!')
      }
      return isJPG && isLt10M
    },
    handleSuccessImg(response, file, fileList) {
      if (response.code === 200) {
        this.form.iconUrl =response.data.url;
      } else {
        this.$message.error('上传失败，请重试');
        this.form.iconUrl  = undefined;
      }
    },
    handleRemove(file, fileList) {
      this.form.iconUrl = fileList
    },

  }
};
</script>
<style lang="scss" scoped>
  ::v-deep.thmb-uploader .el-upload {
    border: 1px dashed #D9D9D9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep.thmb-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .thmb-img {
    width: 100px;
    height: 100px;
    display: block;
  }
  .thmb-uploader-icon {
    font-size: 28px;
    color: #8C939D;
    width: 100px;
    height: 100px;
    line-height: 108px;
    text-align: center;
  }
</style>